package com.LeeCode;

/**
 * 有序链表转换二叉搜索树
 */

public class Code109 {
    public static void main(String[] args) {
        int[] nums = {-10, -3, 0, 5, 9};
        ListNode head = Utils.arrayToListNode(nums);
        TreeNode node = new Code109().sortedListToBST(head);
        System.out.println("done");
    }

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        ListNode slow = head, fast = head, prev = null;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            prev = slow;
            slow = slow.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.right = sortedListToBST(slow.next);
        if(prev != null) {
            prev.next = null;
            root.left = sortedListToBST(head);
        }

        return root;
    }
}
